<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Website extends CI_Controller {
	public function index(){
		if($this->session->userdata('website_id') == '' || $this->session->userdata('website_user') == ''){
			$this->load->helper(array('url'));
			redirect('/website/login', 'location', 301);
		}else{
			$this->layout->setTitle('Website | Manage');
			$page = $this->uri->segment(3) > 1 ? $this->uri->segment(3) : 1;
			$offset = ($page - 1) * PAGE_ITEM;
			$web = $this->session->userdata('website_user');
			if(isset($web)){				
					$filter = " AND website_user = '$web'";				
			}
			$sqlwebsite = "SELECT SQL_CALC_FOUND_ROWS * FROM tdx_website WHERE 1=1 $filter ORDER BY website_id DESC LIMIT $offset, ".PAGE_ITEM;
			$querywebsite = $this->db->query($sqlwebsite);
			// get total
			$sqlTotal = "SELECT FOUND_ROWS() AS found_row";
			$queryTotal = $this->db->query($sqlTotal);
			$dataTotal = $queryTotal->row();
			if($dataTotal->found_row > 0){
				if($dataTotal->found_row > PAGE_ITEM){
					$this->load->library('pagination');
					$config['base_url'] = $this->config->item('base_url').'/website/index/';
					$config['total_rows'] = $dataTotal->found_row;
					$config['per_page'] = PAGE_ITEM;
					$config['num_tag_open'] = '<li>';
					$config['num_tag_close'] = '</li>';
					$config['cur_tag_open'] = '<li><span>';
					$config['cur_tag_close'] = '</span></li>';
					$config['prev_link'] = 'Previous';
					$config['prev_tag_open'] = '<li>';
					$config['prev_tag_close'] = '</li>';
					$config['next_link'] = 'Next';
					$config['next_tag_open'] = '<li>';
					$config['next_tag_close'] = '</li>';
					$config['uri_segment'] = 3;
					$config['first_tag_open'] = '<li>';
					$config['first_tag_close'] = '</li>';
					$config['last_tag_open'] = '<li>';
					$config['last_tag_close'] = '</li>';
					
					$this->pagination->initialize($config);
					$data['paginate'] = $this->pagination->create_links();
				}
				$data['total'] = $dataTotal->found_row;
				if ($querywebsite->num_rows() > 0){
					foreach ($querywebsite->result_array() as $row){
						$data['items'][] = $row;
					}
				}
			}
			$this->layout->view(THEME_DIR.'/website_index', $data);
		}
	}
	public function add(){
		$this->layout->setTitle('Website | Add new website');
		$this->load->helper(array('string_func', 'string'));
		if(!empty($_POST)){
			if($_POST['website_name'] == ''){
				$errMsg[] = 'You must enter some data for website name field';
			}
			if($_POST['website_user'] == ''){
				$errMsg[] = 'You must enter some data for website user field';
			}
			if($_POST['website_password'] == '' || md5($_POST['website_password']) != md5($_POST['website_password2'])){
				$errMsg[] = 'Password does not match';
			}
			
			if($_POST['sms_code'] == ''){
				$errMsg[] = 'Website SMS code is required';
			}
			
			if(empty($errMsg)){
				// check for existing user
				$sqlCheck = "SELECT website_id FROM tdx_website WHERE website_name='".quotes_to_entities($_POST['website_name'])."' OR website_user='".quotes_to_entities($_POST['website_user'])."'";
				$queryCheck = $this->db->query($sqlCheck);
				// check for existing sms code
				$sqlCode = "SELECT website_id FROM tdx_website WHERE sms_code='".quotes_to_entities($_POST['sms_code'])."'";
				$queryCode = $this->db->query($sqlCode);
				if($queryCheck->num_rows() > 0){
					$errMsg[] = "website name or user already existed.";
				}
				elseif($queryCode->num_rows() > 0){
					$errMsg[] = "SMS code <strong>".quotes_to_entities($_POST['sms_code'])."</strong> already existed.";
				}
				else{
					$strSalt = generateSalt();
					$password = generatePassword($_POST['website_password'], $strSalt);
					$arrData = array(
						'customer_id'		=> $_POST['customer'],
						'website_name'		=> $_POST['website_name'],
						'url_link'		=> $_POST['url_link'],
						'sms_code'	=> $_POST['sms_code'],
						'start_date'	=> date('d-m-Y'),
						'website_user'	=> $_POST['website_user'],
						'website_password'	=> $password,
						'website_salt'	=> $strSalt,
					);
					if($this->db->insert('tdx_website', $arrData)){
						$data['msg'] = "New user website has been added.";
					}
					else{
						$errMsg[] = "An error has been occured when adding new Website for Customer. Please contact our admin";
					}
				}
			}
			
			if(!empty($errMsg)){
				$data['error'] = true;
				$data['error_msg'] = $errMsg;
			}
		}
		$this->layout->view(THEME_DIR.'/website_add', $data);
	}
	public function edit(){
		$this->layout->setTitle('Website | Edit website');
		$this->load->helper(array('string_func', 'string'));
		$wid = intval($this->uri->segment(3));
		$sqlwebsite = "SELECT * FROM tdx_website WHERE website_id='$wid'";
		$rswebsite = $this->db->query($sqlwebsite);
		if($rswebsite->num_rows() > 0){
			$data['websiteInfo'] = $rswebsite->row_array();
			if(!empty($_POST)){
				if($_POST['pwdflag'] == 1){
					if($_POST['website_password'] == '' || md5($_POST['website_password']) != md5($_POST['website_password2'])){
						$errMsg[] = 'Password does not match';
					}
				}
				if($_POST['website_name'] == ''){
					$errMsg[] = 'website name is required';
				}
				if($_POST['sms_code'] == ''){
					$errMsg[] = 'website SMS code is required';
				}
				
				if(empty($errMsg)){
					// check for existing user
					$sqlCheck = "SELECT website_id FROM tdx_website WHERE website_name='".quotes_to_entities($_POST['website_name'])."'";
					$queryCheck = $this->db->query($sqlCheck);
					// check for existing sms code
					$sqlCode = "SELECT website_id FROM tdx_website WHERE sms_code='".quotes_to_entities($_POST['sms_code'])."'";
					$queryCode = $this->db->query($sqlCode);
					if($queryCheck->num_rows() > 1){
						$errMsg[] = "website name already existed.";
					}
					elseif($queryCode->num_rows() > 1){
						$errMsg[] = "SMS code <strong>".quotes_to_entities($_POST['sms_code'])."</strong> already existed.";
					}
					else{
						$arrData = array(
							'website_name'		=> $_POST['website_name'],
							'url_link'		=> $_POST['url_link'],
							'sms_code'	=> $_POST['sms_code'],
						);
						if($_POST['pwdflag'] == 1 && $_POST['website_password'] != ''){
							$strSalt = generateSalt();
							$password = generatePassword($_POST['website_password'], $strSalt);
							$arrData['website_password'] = $password;
							$arrData['website_salt'] = $strSalt;
						}
						if($this->db->update('tdx_website', $arrData, array("website_id" => $wid))){
							$data['msg'] = "Update successful.";
							$arrData['website_name'] = $data['websiteInfo']['website_name'];
							$data['websiteInfo'] = $arrData;
						}
						else{
							$errMsg[] = "An error has been occured when updating website. Please contact our admin";
						}
					}
				}
				
				if(!empty($errMsg)){
					$data['error'] = true;
					$data['error_msg'] = $errMsg;
				}
			}
		}
		else{
			$data['error'] = true;
			$data['error_msg'] = array('Website not found');
		}
		$this->layout->view(THEME_DIR.'/website_edit', $data);
	}
	public function login()
	{
		$this->load->helper(array('string_func', 'string', 'url'));
		$result = array();
		if(isset($_POST['website_user'])){
			$website_user = quotes_to_entities($_POST['website_user']);
			$query = $this->db->query("SELECT website_id, website_name, website_user, website_password, website_salt FROM tdx_website WHERE website_user='$website_user'");
			if ($query->num_rows() > 0){
				$row = $query->row_array();
				$website_password = generatePassword($_POST['website_password'], $row['website_salt']);
				$sqlPwd = $this->db->query("SELECT website_id, website_user, website_name, website_salt, url_link, sms_code 
											FROM tdx_website WHERE website_user='".$row['website_user']."' AND website_password='$website_password'");
				if ($sqlPwd->num_rows() > 0){
					$websiteInfo = $sqlPwd->row_array();
					$this->session->set_userdata($websiteInfo);
					redirect('/home/index', 'location', 301);
				}
				else{
					$result['error'] = true;
					$result['msg'] = "Wrong your username or password.";
				}
			}
			
		}
		$this->layout->setLayout('cupcake_login');
		$this->layout->setTitle('Website | Login');
		$this->layout->view(THEME_DIR.'/website_login', $result);
	}
	public function logout(){
		$this->load->helper(array('url'));
		$this->session->unset_userdata(array('website_id' => '', 'website_name' => '', 'website_user' => '','website_salt' => '', 'url_link' => '', 'sms_code' => ''));
		redirect('/website/login', 'location', 301);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */